"""
Content Tag Model
内容标签模型 - 标签系统和多对多关联
"""

import uuid
from enum import Enum

from sqlalchemy import Column, String, DateTime, Integer, Boolean, Text, ForeignKey, Table, JSON
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from ..core.database import Base


# 内容标签关联表
content_tag_associations = Table(
    'content_tag_associations',
    Base.metadata,
    Column('content_id', UUID(as_uuid=True), ForeignKey('generated_contents.id', ondelete='CASCADE'), primary_key=True),
    Column('tag_id', UUID(as_uuid=True), ForeignKey('content_tags.id', ondelete='CASCADE'), primary_key=True),
    Column('created_at', DateTime, default=func.now()),
    Column('confidence', Integer, default=100),  # 标签置信度 (0-100)
    Column('is_auto_generated', Boolean, default=False),  # 是否自动生成的标签
    Column('user_id', UUID(as_uuid=True), ForeignKey('users.id', ondelete='CASCADE'), nullable=True),  # 添加标签的用户
)


class TagCategory(str, Enum):
    """标签分类枚举"""
    CONTENT_TYPE = "content_type"      # 内容类型
    STYLE = "style"                   # 风格
    SUBJECT = "subject"               # 主题
    COLOR = "color"                   # 颜色
    EMOTION = "emotion"               # 情感
    TECHNIQUE = "technique"           # 技术
    SCENE = "scene"                   # 场景
    CUSTOM = "custom"                 # 自定义
    AI_GENERATED = "ai_generated"     # AI生成


class TagVisibility(str, Enum):
    """标签可见性枚举"""
    PUBLIC = "public"      # 公开
    PRIVATE = "private"    # 私有
    SYSTEM = "system"      # 系统


class ContentTag(Base):
    """内容标签模型"""

    __tablename__ = "content_tags"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    
    # 标签信息
    name = Column(String(50), nullable=False, index=True)
    display_name = Column(String(100), nullable=True)  # 显示名称
    description = Column(Text, nullable=True)  # 标签描述
    
    # 分类和属性
    category = Column(String(30), nullable=False, default="custom", index=True)
    color = Column(String(7), nullable=True)  # 标签颜色 (#RRGGBB)
    icon = Column(String(50), nullable=True)  # 图标标识
    
    # 使用统计
    usage_count = Column(Integer, default=0)  # 使用次数
    content_count = Column(Integer, default=0)  # 关联内容数量
    
    # 可见性和权限
    visibility = Column(String(20), nullable=False, default="public")
    is_system = Column(Boolean, default=False)  # 是否为系统标签
    is_active = Column(Boolean, default=True)  # 是否激活
    
    # 语言支持
    language = Column(String(10), default="zh-CN")  # 语言代码
    translations = Column(JSON, default=dict)  # 多语言翻译 {lang: name}
    
    # 层级结构（用于分类标签）
    parent_id = Column(
        UUID(as_uuid=True), 
        ForeignKey("content_tags.id", ondelete="CASCADE"), 
        nullable=True,
        index=True
    )
    
    # 元数据
    content_metadata = Column(JSON, default=dict)  # 其他元数据（避免与SQLAlchemy的metadata冲突）
    synonyms = Column(JSON, default=list)  # 同义词列表
    related_tags = Column(JSON, default=list)  # 相关标签ID列表
    
    # SEO和搜索优化
    slug = Column(String(100), nullable=True, unique=True)  # URL友好的标识符
    keywords = Column(JSON, default=list)  # SEO关键词
    
    # 时间戳
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    last_used_at = Column(DateTime, nullable=True)  # 最后使用时间

    # 关系
    parent = relationship("ContentTag", remote_side=[id], backref="children")
    contents = relationship(
        "GeneratedContent", 
        secondary=content_tag_associations, 
        back_populates="content_tags"
    )

    def __repr__(self):
        return f"<ContentTag(id={self.id}, name={self.name}, category={self.category})>"

    @property
    def is_public(self) -> bool:
        """是否为公开标签"""
        return self.visibility == TagVisibility.PUBLIC

    @property
    def is_private(self) -> bool:
        """是否为私有标签"""
        return self.visibility == TagVisibility.PRIVATE

    @property
    def is_system_tag(self) -> bool:
        """是否为系统标签"""
        return self.is_system or self.visibility == TagVisibility.SYSTEM

    @property
    def is_category_tag(self) -> bool:
        """是否为分类标签（有子标签）"""
        return len(self.children) > 0

    @property
    def is_leaf_tag(self) -> bool:
        """是否为叶子标签（无子标签）"""
        return len(self.children) == 0

    @property
    def has_translations(self) -> bool:
        """是否有翻译"""
        return bool(self.translations)

    def get_display_name(self, language: str = None) -> str:
        """获取显示名称"""
        if language and self.translations and language in self.translations:
            return self.translations[language]
        return self.display_name or self.name

    def add_translation(self, language: str, name: str) -> None:
        """添加翻译"""
        if not self.translations:
            self.translations = {}
        self.translations[language] = name

    def remove_translation(self, language: str) -> bool:
        """移除翻译"""
        if self.translations and language in self.translations:
            del self.translations[language]
            return True
        return False

    def add_synonym(self, synonym: str) -> None:
        """添加同义词"""
        synonyms = self.synonyms or []
        if synonym not in synonyms:
            synonyms.append(synonym)
            self.synonyms = synonyms

    def remove_synonym(self, synonym: str) -> bool:
        """移除同义词"""
        synonyms = self.synonyms or []
        if synonym in synonyms:
            synonyms.remove(synonym)
            self.synonyms = synonyms
            return True
        return False

    def add_related_tag(self, tag_id: str) -> None:
        """添加相关标签"""
        related_tags = self.related_tags or []
        if tag_id not in related_tags:
            related_tags.append(tag_id)
            self.related_tags = related_tags

    def remove_related_tag(self, tag_id: str) -> bool:
        """移除相关标签"""
        related_tags = self.related_tags or []
        if tag_id in related_tags:
            related_tags.remove(tag_id)
            self.related_tags = related_tags
            return True
        return False

    def add_keyword(self, keyword: str) -> None:
        """添加SEO关键词"""
        keywords = self.keywords or []
        if keyword not in keywords:
            keywords.append(keyword)
            self.keywords = keywords

    def remove_keyword(self, keyword: str) -> bool:
        """移除SEO关键词"""
        keywords = self.keywords or []
        if keyword in keywords:
            keywords.remove(keyword)
            self.keywords = keywords
            return True
        return False

    def increment_usage(self) -> None:
        """增加使用次数"""
        self.usage_count += 1
        self.content_count += 1
        self.last_used_at = func.now()

    def decrement_usage(self) -> None:
        """减少使用次数"""
        self.usage_count = max(0, self.usage_count - 1)
        self.content_count = max(0, self.content_count - 1)

    def update_content_count(self, delta: int = 1) -> None:
        """更新关联内容数量"""
        self.content_count = max(0, self.content_count + delta)

    def generate_slug(self) -> str:
        """生成URL友好的标识符"""
        import re
        import unicodedata
        
        # 标准化Unicode字符
        slug = unicodedata.normalize('NFKD', self.name)
        slug = slug.encode('ascii', 'ignore').decode('ascii')
        
        # 替换空格和特殊字符
        slug = re.sub(r'[^\w\s-]', '', slug).strip().lower()
        slug = re.sub(r'[-\s]+', '-', slug)
        
        return slug

    def set_slug(self) -> None:
        """设置slug（如果不存在）"""
        if not self.slug:
            self.slug = self.generate_slug()

    def get_ancestors(self) -> list:
        """获取所有祖先标签"""
        ancestors = []
        current = self.parent
        while current:
            ancestors.append(current)
            current = current.parent
        return ancestors

    def get_descendants(self, include_self: bool = False) -> list:
        """获取所有后代标签"""
        descendants = []
        if include_self:
            descendants.append(self)
        
        for child in self.children:
            descendants.append(child)
            descendants.extend(child.get_descendants())
        
        return descendants

    def is_ancestor_of(self, other) -> bool:
        """检查是否为另一个标签的祖先"""
        if not other:
            return False
        
        current = other.parent
        while current:
            if current.id == self.id:
                return True
            current = current.parent
        return False

    def is_descendant_of(self, other) -> bool:
        """检查是否为另一个标签的后代"""
        if not other:
            return False
        
        current = self.parent
        while current:
            if current.id == other.id:
                return True
            current = current.parent
        return False

    def to_dict(self, include_children: bool = False) -> dict:
        """转换为字典"""
        data = {
            "id": str(self.id),
            "name": self.name,
            "display_name": self.get_display_name(),
            "description": self.description,
            "category": self.category,
            "color": self.color,
            "icon": self.icon,
            "visibility": self.visibility,
            "is_system": self.is_system,
            "is_active": self.is_active,
            "usage_count": self.usage_count,
            "content_count": self.content_count,
            "language": self.language,
            "translations": self.translations or {},
            "synonyms": self.synonyms or [],
            "keywords": self.keywords or [],
            "slug": self.slug,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "last_used_at": self.last_used_at.isoformat() if self.last_used_at else None,
        }
        
        if include_children and self.children:
            data["children"] = [child.to_dict(include_children=True) for child in self.children]
        
        return data


# 预定义的系统标签
SYSTEM_TAGS = [
    # 内容类型
    {"name": "image", "display_name": "图片", "category": TagCategory.CONTENT_TYPE, "color": "#FF6B6B"},
    {"name": "video", "display_name": "视频", "category": TagCategory.CONTENT_TYPE, "color": "#4ECDC4"},
    {"name": "audio", "display_name": "音频", "category": TagCategory.CONTENT_TYPE, "color": "#45B7D1"},
    {"name": "text", "display_name": "文本", "category": TagCategory.CONTENT_TYPE, "color": "#96CEB4"},
    
    # 风格
    {"name": "realistic", "display_name": "写实风格", "category": TagCategory.STYLE, "color": "#FECA57"},
    {"name": "cartoon", "display_name": "卡通风格", "category": TagCategory.STYLE, "color": "#FF9FF3"},
    {"name": "anime", "display_name": "动漫风格", "category": TagCategory.STYLE, "color": "#54A0FF"},
    {"name": "abstract", "display_name": "抽象风格", "category": TagCategory.STYLE, "color": "#5F27CD"},
    
    # 质量
    {"name": "high-quality", "display_name": "高质量", "category": TagCategory.TECHNIQUE, "color": "#00D2D3"},
    {"name": "medium-quality", "display_name": "中等质量", "category": TagCategory.TECHNIQUE, "color": "#FF9F43"},
    {"name": "low-quality", "display_name": "低质量", "category": TagCategory.TECHNIQUE, "color": "#EE5A24"},
    
    # 情感
    {"name": "happy", "display_name": "快乐", "category": TagCategory.EMOTION, "color": "#FED330"},
    {"name": "sad", "display_name": "悲伤", "category": TagCategory.EMOTION, "color": "#45B7D1"},
    {"name": "exciting", "display_name": "兴奋", "category": TagCategory.EMOTION, "color": "#FD79A8"},
    {"name": "calm", "display_name": "平静", "category": TagCategory.EMOTION, "color": "#A29BFE"},
]


def create_system_tags(session) -> None:
    """创建系统标签"""
    for tag_data in SYSTEM_TAGS:
        tag = ContentTag(
            name=tag_data["name"],
            display_name=tag_data["display_name"],
            category=tag_data["category"],
            color=tag_data["color"],
            is_system=True,
            visibility=TagVisibility.PUBLIC,
            is_active=True
        )
        session.add(tag)